package com.charles.seckillPlatform.rocketMQ.consumer;

import com.alibaba.fastjson2.JSONObject;
import com.charles.seckillComponentCommon.constants.CacheConstants;
import com.charles.seckillComponentCommon.utils.StringUtils;
import com.charles.seckillComponentRedis.service.RedisService;
import com.charles.seckillData.domain.SysGood;
import com.charles.seckillData.domain.SysOrder;
import com.charles.seckillPlatform.mapper.SysOrderMapper;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author Charles-H
 * <p>
 * 订单消费者
 */
@Component
@RocketMQMessageListener(topic = "checkOrder", consumerGroup = "checkOrderGroup")
public class OrderConsumer implements RocketMQListener<String> {

    public static final Logger logger = LoggerFactory.getLogger(OrderConsumer.class);

    @Autowired
    private SysOrderMapper sysOrderMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void onMessage(String msg) {
        try {
            Map<String, Long> map = JSONObject.parseObject(msg, Map.class);
            String userId = String.valueOf(map.get("userId"));
            String goodId = String.valueOf(map.get("goodId"));
            String orderId = (String) redisService.getCacheObject(CacheConstants.STORE_ORDER_ID + userId + goodId);

            if (StringUtils.isNotEmpty(orderId)) {
                SysOrder order = (SysOrder) redisService.getCacheObject(CacheConstants.ORDER_ID + orderId);
                if (order != null) {
                    // 如果没支付成功，就设为过期状态，也存入数据库中。
                    if (!order.getStatus().equals("1")) {
                        order.setStatus("2");
                        // 如果订单未支付,则让增加产品库存
                        RLock lock = redissonClient.getLock("handle-unpaid-order");
                        try {
                            lock.lock();
                            SysGood good = (SysGood) redisService.getCacheObject(CacheConstants.GOOD_ID + goodId);
                            if (good != null) {
                                good.setRemain(good.getRemain() + 1);
                                redisService.setCacheObject(CacheConstants.GOOD_ID + goodId, good);
                            }
                        } finally {
                            lock.unlock();
                        }
                    }
                    sysOrderMapper.addOrder(order);
                    redisService.deleteObject(CacheConstants.STORE_ORDER_ID + userId + goodId);
                    redisService.deleteObject(CacheConstants.ORDER_ID + orderId);
                }
            }
        } catch (Exception e) {
            logger.error("消费者服务异常：", e);
        }
    }
}
